#include <conio.h> 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h> 

int main(int argc, char *argv[])
{
	int sim, podozr, chetchik, i, div, rem;
	if ( argc != 4)
	{
		printf("Error, wrong arguments. Use <>.exe c/d infile outfile\n");
		system ("PAUSE");
	}
	if (strcmp(argv[1], "c") == 0)
	{
		FILE * inFile;
		FILE * outFile;
		inFile = fopen(argv[2], "rb");
		outFile = fopen(argv[3], "wb");
		sim = fgetc(inFile);
		while (1)
		{
			if (sim == EOF)
			{
				break;
			}
			if (sim == '&')
			{
				podozr = sim;
				chetchik=1;
				while (1)
				{
					sim = fgetc(inFile);
					if (sim == EOF)
					{
						break;
					}
					if (sim == podozr)
					{
						chetchik++;
					}
					else
					{
						break;
					}
				}
				if (chetchik > 0)
				{
					while (chetchik>=255)
					{
						chetchik -= 255;
						fputc( '&' , outFile );
						fputc( 255 , outFile );
						fputc( podozr , outFile );

					}
					if (chetchik > 0)
					{
						fputc('&' , outFile );
						fputc( chetchik , outFile );
						fputc( podozr , outFile );
					}
				}
				
			}
			else
			{
				podozr = sim;
				chetchik=1;
				while (1)
				{
					sim = fgetc(inFile);
					if (sim == EOF)
					{
						break;
					}
					if (sim == podozr)
					{
						chetchik++;
					}
					else
					{
						break;
					}
				}
				if (chetchik > 3)
				{
					while (chetchik>=255)
					{
						chetchik -= 255;
						fputc( '&' , outFile );
						fputc( 255 , outFile );
						fputc( podozr , outFile );

					}
					if (chetchik > 3)
					{
						fputc('&' , outFile );
						fputc( chetchik , outFile );
						fputc( podozr , outFile );
					}
					else if (chetchik>0)
					{
						for (i=1; i<=chetchik; i++)
						{
							fputc( podozr , outFile );
						}
					}
				}
				else
				{

					for (i=1; i<=chetchik; i++)
					{
						fputc( podozr , outFile );
					}

				}
				}
		}
		fclose(inFile);
		fclose(outFile);
	}
	else
	{
		if (strcmp(argv[1], "d") == 0)
		{
			FILE * inFile;
			FILE * outFile;
			inFile = fopen(argv[2], "rb");
			outFile = fopen(argv[3], "wb");
			while (1)
			{
				sim = fgetc(inFile);
				if (sim = '&')
				{
					chetchik = fgetc(inFile);
					sim = fgetc(inFile);
					for (i=1; i<=chetchik; i++)
					{
						fputc( sim , outFile );
					}
				}
				else
				{
					fputc( sim , outFile );
				}
			}
			fclose(inFile);
			fclose(outFile);
		}
		else
		{
			printf("Error, wrong second argument. Use c/d \n");
			system ("PAUSE");
		}
	}
}